<template>
  <view v-if="shenheStatus == 0" class="page">
    <template v-if="type">
      <u-popup v-model="showAd" mode="bottom" :safe-area-inset-bottom="true">
        <view class="picker-view-title">
          <div class="left" @click="showAd = false">取消</div>
          <div class="right" @click="confirm">确定</div>
        </view>
        <picker-view
          indicator-style="height:50rpx;"
          :value="defaultIndex"
          @change="selectChange"
          class="picker-view"
        >
          <picker-view-column>
            <view
              class="picker-view-item"
              v-for="(item, index) in districtList_1"
              :key="index"
              >{{ item.name }}</view
            >
          </picker-view-column>
          <picker-view-column>
            <view
              class="picker-view-item"
              v-for="(item, index) in districtList_2"
              :key="index"
              >{{ item.name }}</view
            >
          </picker-view-column>
          <picker-view-column>
            <view
              class="picker-view-item"
              v-for="(item, index) in districtList_3"
              :key="index"
              >{{ item.name }}</view
            >
          </picker-view-column>
        </picker-view>
      </u-popup>

      <view class="m-form">
        <view class="item">
          <view class="label">姓名</view>
          <view class="inp">
            <input v-model="form.name" placeholder="请输入姓名" />
          </view>
        </view>

        <view class="item">
          <view class="label">电话</view>
          <view class="inp">
            <input v-model="form.mobile" placeholder="请输入电话" />
          </view>
        </view>

        <view class="item" @click="showAd = true">
          <view class="label">地址</view>
          <view class="inp">
            <input
              style="pointer-events: none"
              disabled
              :value="position"
              placeholder="请选择地址"
            />
          </view>
          <!-- <view class="addr">
            <i class="iconfont icon-a-map"></i>
            <view class="test" @click="getPosition">定位</view>
          </view> -->
        </view>

        <view class="item">
          <view class="label">详细地址</view>
          <view class="inp">
            <input
              v-model="form.address"
              type="textarea"
              clearable
              placeholder="请输入详细地址"
            />
          </view>
        </view>
      </view>

      <view class="btn" @click="submit">提交申请</view>
    </template>
    <template v-else>
      <view class="status">
        <i class="iconfont icon-clock-fill"></i>
        <view class="title">正在审核中</view>
        <view class="des">正在审核，请耐心等待</view>
      </view>
      <view class="btn" @click="clearTime">返回（{{ num }}）</view>
    </template>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import { getAuditInfo, applySubmit } from "@/api/teamGrades";
var district = [];
export default {
  components: {
    Shenhe
  },
  data() {
    return {
      form: {
        name: "",
        mobile: "",
        // longitude: "",
        // latitude: "",
        address: ""
      },

      province_id: "",
      city_id: "",
      district_id: "",

      type: 1,

      districtList_1: [],
      districtList_2: [],
      districtList_3: [],
      defaultIndex: [0, 0, 0],

      showAd: false,
      position: "",

      num: 3,

      timer: null
    };
  },
  async onLoad() {
    const res = await getAuditInfo();
    if (!res.code) {
      let { status, audit_info } = res.data;

      switch (status) {
        case 0:
          this.$utils.toUrl("/tools/teamGrades/task", "redirectTo");
          break;
        case 1:
          this.getDistrict(async () => {});
          break;
        case 2:
          this.type = 0;
          this.countdown();
          break;
      }
    }
  },

  methods: {
    clearTime() {
      clearTimeout(this.timer);
      this.$utils.toUrl("/tools/teamGrades/task", "redirectTo");
    },
    countdown() {
      this.num--;
      this.timer = setTimeout(() => {
        if (this.num) {
          this.countdown();
        } else {
          this.$utils.toUrl("/tools/teamGrades/task", "redirectTo");
        }
      }, 1000);
    },

    selectChange(e) {
      let indexs = e.detail.value;
      let yDefaultIndex = JSON.parse(JSON.stringify(this.defaultIndex));
      if (yDefaultIndex[0] != indexs[0]) {
        this.defaultIndex = [indexs[0], 0, 0, 0, 0];
      } else if (yDefaultIndex[1] != indexs[1]) {
        this.defaultIndex = [indexs[0], indexs[1], 0, 0, 0];
      } else if (yDefaultIndex[2] != indexs[2]) {
        (this.defaultIndex = [indexs[0], indexs[1], indexs[2], 0]), 0;
      } else if (yDefaultIndex[3] != indexs[3]) {
        this.defaultIndex = [indexs[0], indexs[1], indexs[2], indexs[3], 0];
      } else if (yDefaultIndex[4] != indexs[4]) {
        this.defaultIndex = [indexs[0], indexs[1], indexs[2]];
      }

      this.districtList_2 = district[this.defaultIndex[0]].cityAll;
      this.districtList_3 =
        district[this.defaultIndex[0]].cityAll[
          this.defaultIndex[1]
        ].districtAll;

      // this.districtList_4 =
      //   district[this.defaultIndex[0]].cityAll[
      //     this.defaultIndex[1]
      //   ].districtAll[this.defaultIndex[2]].townAll;
      // if (this.districtList_4.length > 0) {
      //   this.districtList_5 =
      //     district[this.defaultIndex[0]].cityAll[
      //       this.defaultIndex[1]
      //     ].districtAll[this.defaultIndex[2]].townAll[
      //       this.defaultIndex[3]
      //     ].villageAll;
      // } else {
      //   this.districtList_5 = [];
      // }
    },

    async getDistrict(fn) {
      try {
        var res = await this.$allrequest.user.get_district({});
        district = JSON.parse(JSON.stringify(res.data));

        this.districtList_1 = res.data.map((item) => {
          delete item.cityAll;
          return item;
        });

        this.setAddressList();
        fn && fn();
      } catch (e) {
        //TODO handle the exception
      }
    },

    setAddressList(list = []) {
      let cityList,
        districtList,
        provinceIndex = 0,
        cityIndex = 0,
        districtIndex = 0;

      if (list && list.length) {
        cityList = district.find((el) => String(list[0]) === el.id).cityAll;
        districtList = cityList.find(
          (el) => String(list[1]) === el.id
        ).districtAll;

        provinceIndex = district.findIndex((el) => String(list[0]) === el.id);
        cityIndex = cityList.findIndex((el) => String(list[1]) === el.id);
        districtIndex = districtList.findIndex(
          (el) => String(list[2]) === el.id
        );
      } else {
        let cityAllItem = JSON.parse(JSON.stringify(district[0].cityAll));
        cityList = cityAllItem;
        districtList = cityList[0].districtAll;
      }

      this.districtList_2 = JSON.parse(JSON.stringify(cityList)).map((el) => {
        delete el.districtAll;
        return el;
      });
      this.districtList_3 = districtList;
      this.defaultIndex = [provinceIndex, cityIndex, districtIndex];
    },

    async getPosition() {
      const apiRes = await this.$store.dispatch("getLocation");
      if (apiRes.longitude) {
        uni.chooseLocation({
          success: (res) => {
            this.longitude = res.longitude;
            this.latitude = res.latitude;
            this.details = res.name;
            this.getAddress(res.address + res.name);
          },
          fail: () => {
            this.$u.toast(this.$t("my.failPosition"));
          }
        });
      }
    },

    getAddress(address) {
      this.$allrequest.classification
        .addressSmart({
          address
        })
        .then((res) => {
          if (res.code == 0) {
            this.province_id = res.data.province_id;
            this.city_id = res.data.city_id;
            this.district_id = res.data.region_id;
            this.position = res.data.province + res.data.city + res.data.region;
          }
        });
    },

    confirm() {
      this.showAd = false;

      let val = this.defaultIndex;
      let i1 = val[0];
      let i2 = val[1];
      let i3 = val[2];
      // let i4 = val[3];
      // let i5 = val[5];
      this.province_id = this.districtList_1[i1].id;
      this.city_id = this.districtList_2[i2].id;
      this.district_id = this.districtList_3[i3].id;
      // if (this.districtList_4.length > 0) {
      //   this.town_id = this.districtList_4[i4].id;
      // } else {
      //   this.town_id = 0;
      // }
      // if (this.districtList_5.length > 0) {
      //   if (i5) {
      //     this.village_id = this.districtList_5[i5].id;
      //   } else {
      //     this.village_id = this.districtList_5[0].id;
      //   }
      // } else {
      //   this.village_id = 0;
      // }
      this.position = [];
      this.position[0] = this.districtList_1[i1].name;
      this.position[1] = this.districtList_2[i2].name;
      this.position[2] = this.districtList_3[i3].name;
      // if (this.districtList_4.length > 0) {
      //   this.position[3] = this.districtList_4[i4].name;
      // }
      // if (this.districtList_5.length > 0) {
      //   if (i5) {
      //     this.position[4] = this.districtList_5[i5].name;
      //   } else {
      //     this.position[4] = this.districtList_5[0].name;
      //   }
      // }
      this.position = this.position.join(",");
    },

    submit() {
      uni.$u.throttle(async () => {
        try {
          let { form, province_id, city_id, district_id } = this;
          if (!form.name) return this.$utils.toast("请输入姓名");

          if (!form.mobile) return this.$utils.toast("请输入手机号");

          if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(form.mobile))
            return this.$utils.toast("请输入正确的手机号");

          if (!this.province_id) return this.$utils.toast("请选择所在地区");

          if (!form.address) return this.$utils.toast("请输入详细地址");

          const res = await applySubmit(
            {
              ...form,
              province_id,
              city_id,
              district_id
            },
            true
          );

          if (!res.code) {
            this.$utils.showModal("提示", "提交成功", false, () => {
              this.type = 0;
              this.num = 3;
              this.countdown();
            });
            return;
          }
        } catch (error) {
          this.$utils.toast(error);
        }
      }, 1000);
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f2f2f2;
  overflow: hidden;
}

.m-form {
  margin: 24rpx 24rpx 0;
  padding: 0 24rpx;
  border-radius: 20rpx;
  background: #fff;
  font-size: 28rpx;
}

.item {
  display: flex;
  align-items: center;
  height: 88rpx;
  border-bottom: 2rpx solid #f8f8f8;

  &:last-of-type {
    border-bottom: 0;
  }
}

.label {
  width: 140rpx;
  font-weight: bold;
}

.inp {
  padding: 0 30rpx;
  flex: 1;
  overflow: hidden;
}

.addr {
  display: flex;
  align-items: center;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 80rpx 36rpx 0;
  height: 80rpx;
  background: #f0250e;
  border-radius: 32px;
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
}

.status {
  padding: 30rpx 0 70rpx;
  text-align: center;
  background: #fff;

  .iconfont {
    font-size: 180rpx;
    color: #f0250e;
  }

  .title {
    padding-bottom: 20rpx;
    font-size: 40rpx;
    font-weight: bold;
  }

  .des {
    font-size: 30rpx;
    color: #8c8c8c;
  }
}

.picker-view-title {
  padding: 20rpx;
  font-size: 28rpx;
  color: #1aa034;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    color: #999;
  }
}

.picker-view {
  width: 750rpx;
  height: 500rpx;
  .picker-view-item {
    height: 50rpx;
    line-height: 50rpx;
    align-items: center;
    justify-content: center;
    text-align: center;
  }
}
</style>
